package com.ar4j.handler;

import java.util.Collection;
import java.util.Map;

import com.ar4j.ActiveRecordMetadata;

/**
 * Various common handler utilities
 */
public final class HandlerUtils {
  
  private HandlerUtils() {
    // UTILITY CLASS - NO CONSTRUCTOR FOR YOU!
  }
  
  /**
   * Goes through the given parameters, makes sure that all parameter names are properties in the provided
   * active record metadata. Records field names and collection field flags in the given maps.
   * 
   * @param parameters
   * @param metadata
   * @param fields
   * @param collectionFields
   */
  public static void scanParametersForFields(Map<String, Object> parameters, ActiveRecordMetadata metadata, 
      Collection<String> fields, Collection<String> collectionFields) {
    
    for(Map.Entry<String, Object> entry : parameters.entrySet()) {
      if(!metadata.getPropertyNames().contains(entry.getKey())) {
        throw new IllegalArgumentException("Unknown field in parameter map: " + entry.getKey() + " for base class: " + metadata.getBaseClass());
      }
      
      fields.add(entry.getKey());
      if(entry.getValue() != null && (entry.getValue().getClass().isArray() || Collection.class.isAssignableFrom(entry.getValue().getClass()))) {
        collectionFields.add(entry.getKey());
      }
    }
  }
}
